package detect.parse.tree.token;

import java.util.*;


public class TokenScanner {
	static Scanner scanner=null;
	public static TokenList getTokenList(PositionString psStr){
		if(scanner==null){
			scanner=new Scanner(psStr.str);
		}
		else{
			scanner.reset(psStr.str);
		}
		
		List<Token> tokens=new ArrayList<Token>(200);
		
		TokenType type=null;
		String nameStr=null;
		Token token=null;
		int beginPos=-1;
		while(true){
			nameStr=null;
			scanner.nextToken();
			type=scanner.token();
			if(type==TokenType.EOF){
				break;
			}
			nameStr=type.typeStr;
			beginPos=scanner.pos();
			if(nameStr==null){
				nameStr=scanner.getRawString();
			}
			token=new Token(nameStr,beginPos+psStr.beginPosition);
			token.setTokenType(type);
			tokens.add(token);
		}
		tokens=prettyTokenList(tokens);
		return new TokenList(psStr,tokens);
	}
	
	private static List<Token> prettyTokenList(List<Token> originTokens){
		ArrayList<Token> newTokens=new ArrayList<Token>(originTokens.size());
		
		Token curToken=null;
		Token preOrginToken=null;
		Token preNewToken=null;
		Token nextToken=null;
		for(int i=0;i<originTokens.size();i++){
			curToken=originTokens.get(i);
			preOrginToken=(i>0)?originTokens.get(i-1):null;
			preNewToken=(newTokens.size()>0)?newTokens.get(newTokens.size()-1):null;
			nextToken=(i<originTokens.size()-1)?originTokens.get(i+1):null;
			if(curToken.type==TokenType.STRUCT){
				continue;
			}
			
			if(curToken.type==TokenType.STAR &&
					preNewToken!=null && 
					preNewToken.rawType==RawTokenType.TYPE){
				continue;
			}
			if(curToken.type==TokenType.AMP){
				if(preNewToken==null || preNewToken.rawType!=RawTokenType.IDENTIFIER){
					continue;
				}
			}
			if(curToken.rawType == RawTokenType.IDENTIFIER){
				if(preOrginToken.type==TokenType.STRUCT){
					curToken.setTokenType(TokenType.STRUCTLITERAL);
				}
			}
			newTokens.add(curToken);
		}
		
		return newTokens;
	}
}
